import React, {
    PureComponent
} from 'react';

import {
    Text
} from 'react-native';

interface Props {
    total: number,
    onEnd:Function
}

interface State {
    time: number
}

class Counter extends PureComponent<Props, State> {
    constructor(props: Props) {
        super(props)
        this.state = {
            time: props.total
        }
    }

    timer:any = null;

    static defaultProps = {
        total:60,
        onEnd:() => null
    }

    static check = (num:number) => {
        return `${num}`.length < 2 ? `0${num}` : num;
    }

    static showTime  = (time:number) => {
        const totalSeconds = time;
        let modulo = totalSeconds % (60 * 60 * 24);
        const hours = Math.floor(totalSeconds / (60 * 60));
        modulo = modulo % (60 * 60);
        const minutes = Math.floor(modulo / 60);
        const seconds = modulo % 60;
        return [~~hours, ~~minutes, ~~seconds].map(item => Counter.check(item)).join(` : `);
    }

    componentDidMount() {
        this.timer = (
            setInterval(this.onRun,1000)
        )
    }

    onRun = () => {
        let {
            time
        } = this.state;

        const {
            onEnd
        } = this.props;

        time = time - 1;

        if(time <= 0) {
            this.clearTimer()
            return onEnd();
        }

        this.setState({
            time:time
        })
    }

    clearTimer = () => {
        if(this.timer) {
            clearInterval(this.timer)
            this.timer = null;
        }
    }

    get showTime() {
        const {
            time
        } = this.state;
        return Counter.showTime(time)
    }

    render() {
        return (
            <Text {...this.props}>
                {this.showTime}
            </Text>
        )
    }

    componentWillUnmount() {
        this.clearTimer();
    }
}

export default Counter;